package com.h.heal.filter;

import com.h.heal.common.SessionParameter;
import com.h.heal.entity.Admin;
import com.h.heal.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录过滤器
@WebFilter("/*")   //  /*表示验证过滤所有的url
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest hsr=(HttpServletRequest)servletRequest;
        HttpServletResponse hsrp=(HttpServletResponse)servletResponse;

        String url = hsr.getRequestURL().toString().toLowerCase();
        Object attributeAdmin = hsr.getSession().getAttribute(SessionParameter.ADMIN_INFO);
        Object attributeUser = hsr.getSession().getAttribute(SessionParameter.USER_INFO);
        //白名单：不需要验证过滤的url,比如：登录页面，注册页面等
        if (url.contains("login")
                || url.contains("register")
                || url.contains("style")
                || url.contains("welcome")) {

            filterChain.doFilter(servletRequest, servletResponse); //跳转到下一个过滤器
        } else {
            if (attributeAdmin != null && attributeAdmin instanceof Admin) {
                //用户已经登录
                filterChain.doFilter(servletRequest, servletResponse); //跳转到下一个过滤器
            } else if (attributeUser != null && attributeUser instanceof User) {
                filterChain.doFilter(servletRequest, servletResponse); //跳转到下一个过滤器
            } else {
                hsrp.sendRedirect("/html/welcome/welcome.html"); //用户没有登录，跳转到登录页面
            }
        }
    }
}
